<template>
  <el-drawer
    ref="drawerBox"
    v-bind="$attrs"
    :wrapper-closable="true"
    :close-on-press-escape="false"
    :title="title"
    :size="showMobilePage?'100%':'80%'"
    append-to-body
    v-on="$listeners"
  >
    <div class="drawer-content">
      <filter-input
        v-model="paramsObj"
        :filter-list="filterList"
        show-search-btn
        line-feed
        @handelClick="queryClick"
        @queryEmpty="queryEmpty"
      />
      <div :style="multiple?'':{marginTop: '17px'}" class="table-list">
        <div v-loading="listLoading">
          <template>
            <u-table
              ref="tableRef"
              :data="list.items"
              :row-class-name="(data) => tableRowClassName(data)"
              :height="setTableHeight"
              :border="true"
              class="fb-table"
              beautify-table
              header-drag-style
              header-cell-class-name="order-data-header-cell"
              element-loading-text="加载中..."
              empty-text="暂无数据"
              fit
              select-callback
              hightlight-current-rowref="tableRef"
              @sort-change="sortMethod"
              @select="selectTable"
              @select-all="selectTable">
              <u-table-column
                v-if="multiple && !hideSelectTab"
                fixed="left"
                align="center"
                type="selection"
                width="50"
              />
              <u-table-column v-else-if="!hideSelectTab" fixed="left" align="center" label="" min-width="50">
                <template slot-scope="scope">
                  <el-radio v-model="singleSelectId" :label="scope.row.id" @change="changeRadio($event, scope.row)"><span/></el-radio>
                </template>
              </u-table-column>
              <u-table-column align="left" label="询单编号">
                <template slot-scope="scope">
                  <div v-if="scope.row.sn" style="cursor:pointer;color:#406EFF;" @click="toDetail(scope.row)">
                    <ToolTip :content="handleSnNumber(scope.row.sn)" is-can-click @handelClick="toDetail(scope.row)" />
                  </div>
                  <div v-else>--</div>
                </template>
              </u-table-column>
              <u-table-column align="left" label="品牌名称">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.brandName" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="产品名称">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.productName" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="下单平台">
                <template slot-scope="scope">
                  <div class="flex">
                    <platformIcon :data="scope.row.platformName" />
                    <ToolTip :content="scope.row.platformName" />
                  </div>
                </template>
              </u-table-column>
              <u-table-column align="left" label="合作形式">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.cooperationForm" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="创建人">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.creator" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="创建时间">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.createDate | format('YYYY/MM/DD HH:mm')" />
                </template>
              </u-table-column>
            </u-table>
          </template>
        </div>
        <el-row v-if="showMobilePage" type="flex" justify="left">
          <el-pagination
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[10, 20, 50, 100, 250, 500]"
            :layout="pageLayout"
            :small="true"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </el-row>
        <fixed-pagination class="bottom-pagination">
          <div class="delete-button-container">
            <template v-if="!hideSelectTab">
              <el-button :disabled="!multiple && !singleSelect.id || multiple && !hasSeleted" size="small" type="primary" class="related-btn" @click="confirmRelatedQueryOrder">关联询单</el-button>
              <el-button size="small" plain type="primary" class="related-btn" @click="onBackClick">返回</el-button>
            </template>
          </div>
          <el-pagination
            v-if="!showMobilePage"
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[10, 20, 50, 100, 250, 500]"
            :layout="showMobilePage ? pageLayout : 'total, prev, pager, next, sizes, jumper'"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </fixed-pagination>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import { getDepartmentAll } from '@/api/config';
import { queryOrderList } from '@/api/flyNotice';
import tableSelections from '@/mixins/tableSelections';
import { standardFormatNoHour } from '@/filters/date';
import { moneyFilter } from '@/filters/number';
import { getDeptFullName } from '@/filters/dept';
import { mapOptions } from '@/filters';
import { contractType } from '@/filters/status';
import TableAdaptive from '@/mixins/tableAdaptive';
import options from '@/views/legal/module/options';
import ResourceInfo from '@/components/ResourceInfo';
import PlatformIcon from '@/components/Common/platformIcon';
import FilterInput from '@/components/Tool/filter';
import axios from 'axios';
import { format } from '@/filters/date';
import { mapState } from 'vuex';
import mobileTable from '@/mixins/mobileTable';

export default {
  name: 'RelatedContract',
  filters: {
    format,
    standardFormatNoHour,
    getDeptFullName,
    moneyFilter,
    contractType,
    mapOptions
  },
  components: {
    FilterInput,
    ResourceInfo,
    PlatformIcon
  },
  mixins: [tableSelections, TableAdaptive, mobileTable],
  props: {
    title: {
      type: String,
      default: '选择询单'
    },
    multiple: {
      type: Boolean,
      default: false
    },
    excludeCancel: {
      type: Boolean,
      default: false
    },
    confirmText: {
      type: String,
      default: '关联询单'
    },
    isShowOther: {
      type: Boolean,
      default: false
    },
    formMakeElement: { // 如果不为null，代表是自定义审批的关联
      type: Object,
      default: null
    },
    hideSelectTab: {
      type: Boolean,
      default: false
    },
    showFilterOppCompanyId: {
      type: Boolean,
      default: false
    },
    expandParams: {
      type: Object,
      default: null
    },
    exitSnapshot: {// 是否存在快照数据
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      filterInput: {},
      singleSelect: {
        id: ''
      }, // 单选
      page: 1,
      perPage: 10,
      list: {
        items: [],
        page: 1,
        perPage: 10,
        total: 0
      },
      selectedPage: 1,
      selectedPerPage: 10,
      sortType: '',
      sortName: '',
      listLoading: false,
      options,
      idKey: 'id', // 多选框参数
      isUmyTable: true,
      tableRefName: 'tableRef',
      deptTreeList: [],
      selectedData: [],
      cancelToken: null,
      snapshotData: []
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    tableOutsideHeight() {
      return this.multiple ? (this.showMobilePage ? 270 : 206) : 175;
    },
    hasSeleted() {
      return this.multipleSelectionAll.length > 0;
    },
    filterList() {
      const arr = [
        { keyword: 'sn', name: '询单编号', type: 'input' },
        { keyword: 'brandName', name: '品牌名称', type: 'input' }
      ];
      return arr;
    },
    selectedTableData() {
      return this.selectedData.slice((this.selectedPage - 1) * this.selectedPerPage, this.selectedPage * this.selectedPerPage);
    },
    paramsObj: {
      get() {
        if (this.isOtherTab) return this.otherFilterInput;
        return this.filterInput;
      },
      set(data) {
        if (this.isOtherTab) {
          this.otherFilterInput = data;
        } else {
          this.filterInput = data;
        }
      }
    },
    singleSelectId: {
      get() {
        return this.singleSelect.id;
      },
      set(id) {
        //
      }
    }
  },
  created() {
    this.init();
  },
  methods: {
    // 初始获取数据
    init(data) {
      this.fetchData();
      this.singleSelect = data || {};
    },
    initSelectData(data = []) {
      this.selectedData = data;
      this.multipleSelectionAll = data;
      if (this.exitSnapshot) {
        this.snapshotData = JSON.parse(JSON.stringify(data.filter(i => !!i.id)));
      }
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.fetchData();
    },
    handleLimit(row) {
      if (!row.contractEffectEndDate && !row.contractEffectStartDate) {
        return '/';
      }
      return '-';
    },
    // fitter
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.sortType = '';
      this.sortName = '';
      if (this.isOtherTab) {
        this.otherFilterInput = {};
      } else {
        this.filterInput = {};
      }
      this.queryClick();
    },
    // 翻页
    handleData(tableData) {
      return tableData.slice((this.selectedPage - 1) * this.selectedPerPage, this.selectedPage * this.selectedPerPage);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.fetchData();
    },
    // 获取列表数据
    fetchData(reset = false) {
      try {
        if (reset) this.page = 1;
        this.listLoading = true;
        const params = JSON.parse(JSON.stringify(this.paramsObj));
        params.isRelated = true; // 只展示询单中、已完成的询单
        params.page = this.page;
        params.perPage = this.perPage;
        params.sortName = this.sortName;
        params.sortType = this.sortType;

        if (this.cancelToken) this.cancelToken.cancel('cancel');
        const source = axios.CancelToken.source();
        this.cancelToken = source;
        queryOrderList(params, source.token).then(({ data }) => {
          this.list = data;
          this.listLoading = false;
          if (!this.isSelectedTab) this.setSelectRow(data.items);
          if (this.exitSnapshot && this.snapshotData.length) { // 最新内容替换快照数据
            const list = JSON.parse(JSON.stringify(this.snapshotData));
            list.forEach(j => {
              const findItem = data.items && data.items.find(i => i.id === j.id);
              if (findItem) {
                const snapshotIndex = this.snapshotData.findIndex(k => k.id === j.id);
                this.snapshotData.splice(snapshotIndex, 1);
                const selectIndex = this.multipleSelectionAll.findIndex(k => k.id === j.id);
                this.multipleSelectionAll[selectIndex] = findItem;
              }
            });
          }
        }, () => {
          this.listLoading = false;
        }).catch(e => {
          console.error(e);
        });
      } catch (error) {
        console.log(error);
      }
    },
    // 关联询单
    confirmRelatedQueryOrder() {
      const data = this.multiple ? this.selectedData : this.singleSelect;
      this.$emit('confirmRelatedQueryOrder', _.cloneDeep(data));
      this.$nextTick(() => {
        this.init();
      });
    },
    changeRadio(e, data) {
      this.singleSelect = data;
    },
    // 保留数据
    tableSelectionChange(selection) {
      this.selectedData = selection;

      if (this.isSelectedTab) this.setSelectRow(this.selectedTableData);
    },
    // 申请部门列表
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    // 跳转询单详情
    toDetail(row) {
      const routeUrl = this.$router.resolve({
        name: 'flyNoticeDetail',
        query: {
          id: row.id
        }
      });
      window.open(routeUrl.href, '_blank');
    },
    onBackClick() {
      this.$refs.drawerBox.closeDrawer();
    }
  }
};
</script>

<style scoped lang="scss">
::v-deep .el-drawer__header {
  height: 48px;
  padding: 0 12px 0 24px;
  margin: 0;
  box-shadow: 2px 4px 5px 0 rgba(221,225,234,0.3);
  display: flex;
  align-items: center;
  > span {
    font-size: 14px;
    color: #333;
  }
  ::v-deep .el-tabs__nav-wrap::after {
    height: 0 !important;
  }
}
::v-deep .el-tabs__header {
  margin: 0;
  border: none;
}
::v-deep .el-drawer__body {
  overflow-y: auto;
  margin-bottom: 56px;
}
::v-deep .el-drawer__header>span{
  font-size: 16px;
}
::v-deep .el-badge__content{
  background: #FB5227;
}
::v-deep .el-badge__content{
  transform: translateY(5px);
}
.tip {
  color: #999;
  font-size: 13px;
  margin-left: 20px;;
}
.drawer-content {
  padding: 22px 24px 0;
  overflow-y: auto;
  .table-list {
    &::v-deep {
     .el-table__header {
        .el-checkbox__inner {
          position: relative;
          left: -2px;
        }
      }
    }
    border-radius: 10px;
    .el-row {
      padding: 0;
    }
    .delete-button-container {
      flex:1;
      height: 32px;
      display: flex;
      align-items: center;
      .related-btn {
        margin-left: 20px;
        padding-left: 12px;
        padding-right: 12px;
      }
    }
    ::v-deep .pagination-flex {
      position: absolute;
      width: 100% !important;
    }
  }
}
::v-deep .el-tabs__nav-wrap::after {
  z-index: -1;
}
::v-deep .el-tabs__active-bar {
  bottom: 1px;
}
.contract-detail-tabs-container {
  &::v-deep {
    .el-tabs__header  {
      margin-bottom: 0 !important;
      border-bottom: 1px solid #ddd;
      .el-tabs__nav {
        border: none !important;
        height: 32px !important;
      }
      .el-tabs__item {
        padding: 0 12px !important;
        height: 32px !important;
        line-height: 32px !important;
        margin-right: 8px;
        border: 1px solid #ddd;
        border-radius: 4px 4px 0px 0px;
        color: #333;
        background: #f7f8fa;
        font-size: 16px;
        &:last-child {
          margin-right: 0px;
        }
        &.is-active {
          border-bottom-color: #FFFFFF !important;
          font-weight: bold;
          background: #fff;
          color: #406eff;
        }
      }
    }
  }
}
</style>
